package org.fastsyncer.core.service.impl;

import java.lang.reflect.Method;
import java.util.List;

import org.fastsyncer.core.service.DriverEventService;
import org.fastsyncer.core.util.ClassUtil;
import org.fastsyncer.manager.driver.Event;
import org.fastsyncer.manager.driver.impl.AbstractDriverEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service("DriverEventService")
public final class DriverEventServiceImpl extends AbstractDriverEvent implements DriverEventService {

    private static final Logger logger = LoggerFactory.getLogger(DriverEventServiceImpl.class);
    
    @Override
    public void start() {
        // 查询org.fastsyncer.manager包下的所有类
        List<Class<?>> clazzs = ClassUtil.getAllClassByPackageName("org.fastsyncer.manager");
        if (clazzs == null || clazzs.isEmpty()) {
            return;
        }

        // 过滤出实现Event接口或继承AbstractDriverEvent的实现类,注册到监听器中
        // 过滤的驱动接口名称
        Class<?> absCls = AbstractDriverEvent.class;
        String iName = Event.class.getName();
        String absName = absCls.getName();
        Class<?> c = null;
        Class<?>[] is = null;
        int len = clazzs.size();
        int ilens = 0;
        String name = null;
        for (int i = 0; i < len; i++) {
            c = clazzs.get(i);
            name = c.getName();
            // 排除类和接口本身
            if(absName.equals(name) || iName.equals(name)){
                continue;
            }
            
            // 是否继承类
            if (absCls.isAssignableFrom(c)) {
                // 注册驱动监听类
                this.regist(c);
                continue;
            }
            // 是否实现接口
            is = c.getInterfaces();
            ilens = is.length;
            for (int j = 0; j < ilens; j++) {
                if (iName.equals(is[j].getName())) {
                    // 注册驱动监听类
                    this.regist(c);
                    break;
                }
            }
        }
    }
    
    private void regist(Class<?> c) {
        Object newInstance = null;
        try {
            // 默认调用监听类的构造函数
            newInstance = c.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            try {
                // 如果无法找不到,说明该类是private私有
                // 默认调用其getInstance方法获取类实例
                Method method = c.getMethod("getInstance", new Class[] {});
                newInstance = method.invoke(method, new Object[] {});
            } catch (Exception e1) {
                logger.error(c.getClass() + " > " + e1.getLocalizedMessage());
            }
        }
        if (null != newInstance) {
            logger.info(c.getName());
            super.addObserver((Event) newInstance);
        }
    }
    
}
